package com.atguigu.tingshu.user.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.plugin.auth.constant.Constants;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.LastUserListenPlayVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;


	@Autowired
	private KafkaService kafkaService;

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo) {

		Long userId = AuthContextHolder.getUserId();
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);

		Criteria criteria = Criteria.where("userId").is(userId)
				.and("trackId").is(userListenProcessVo.getTrackId())
				.and("albumId").is(userListenProcessVo.getAlbumId());
		Query query = Query.query(criteria);
		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);

		if (listenProcess == null) {
			listenProcess = new UserListenProcess();
			listenProcess.setUserId(userId);
			listenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			listenProcess.setTrackId(userListenProcessVo.getTrackId());
			listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			listenProcess.setIsShow(1);
			listenProcess.setCreateTime(new Date());
			listenProcess.setUpdateTime(new Date());

			mongoTemplate.save(listenProcess, collectionName);
		} else {
			listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			listenProcess.setUpdateTime(new Date());
			mongoTemplate.save(listenProcess, collectionName);
		}


		// 判断当前声音该用户在当天有没有播放过
		String trackPayRedisKey = "track:play:" + userListenProcessVo.getTrackId() + ":" + new DateTime().toString("yyyyMMdd") + ":" + userId;
		Boolean hasKey = redisTemplate.hasKey(trackPayRedisKey);
		if (!hasKey) {

			// 构建记录播放量的消息
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));   // 用于消费者幂等性保证
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);   // "0701";  // 播放量
			trackStatMqVo.setCount(1);

			// 发送消息
			kafkaService.sendMsg(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));

			// 在Redis中记录当天播放量记录信息
			redisTemplate.opsForValue().set(trackPayRedisKey, "1", 1, TimeUnit.DAYS);

		}

	}

	@Override
	public BigDecimal getTrackBreakSecond (Long userId, Long trackId){
		Query query = Query.query(Criteria.where("trackId").is(trackId).and("userId").is(userId));
		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		if (listenProcess == null) {
			return new BigDecimal("0");
		} else {
			return listenProcess.getBreakSecond();
		}

	}

	@Override
	public LastUserListenPlayVo getLatelyTrack() {
		//查询当前登录用户最后一次播放的声音进度信息
		Long userId = AuthContextHolder.getUserId();
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);

		//创建一个Query对象，封装查询条件
		Query query = Query.query(Criteria.where("userId").is(userId));
		query.with(Sort.by(Sort.Direction.DESC, "updateTime"));
		query.limit(1);

		//发送查询请求
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);

		LastUserListenPlayVo lastUserListenPlayVo = new LastUserListenPlayVo();
		if (userListenProcess == null){
			lastUserListenPlayVo.setTrackId(48237L);
			lastUserListenPlayVo.setAlbumId(1492L);
		}else {
			lastUserListenPlayVo.setTrackId(userListenProcess.getTrackId());
			lastUserListenPlayVo.setAlbumId(userListenProcess.getAlbumId());
		}

		return lastUserListenPlayVo;
	}
}